<template>
  <div id="testlistpanel">
    <vxe-toolbar class-name="bg-orange light">
      <template #buttons>
        <span class="padding-lr-xs">
          <vxe-button type="text" :loading="loading" content="刷新" class-name="padding-lr-xs"
            class="button-blue padding-lr-xs" @click="refreshMainInfoList" />
        </span>
        <span class="padding-lr-xs">
          <vxe-button type="text" content="全部" class-name="padding-lr-xs" class="button-blue padding-lr-xs"
            @click="searchAll" />
        </span>
        <vxe-select style="width: 120px" class-name="margin-lr-xs" v-model="state" placeholder="状态"
          @change="conditionSelectChange">
          <vxe-option v-for="(item, index) in stateOpts" :key="index" :value="item.value"
            :label="item.label"></vxe-option>
        </vxe-select>
        <span class="padding-lr-xs text-bold">类型</span>
        <vxe-select style="width: 60px" class-name="margin-lr-xs" v-model="selPatType" placeholder="类型"
          @change="conditionSelectChange">
          <vxe-option v-for="(item, index) in patTypeList" :key="index" :value="item.code"
            :label="item.name"></vxe-option>
        </vxe-select>
        <vxe-button type="text" content="删除" class-name="padding-lr-xs" class="button-red padding-lr-xs"
          @click="deleteMainInfo" />

        <span class="padding-lr-xs">
          <vxe-checkbox content="我的报告" v-model="isSelfRpt" :checked-value="1" :unchecked-value="0"
            @change="conditionSelectChange"></vxe-checkbox>
        </span>
      </template>
    </vxe-toolbar>
    <div
      :style="{ height: isShowItemTemplatePanel ? 'calc(100% - 30px - 40px - 2px)' : 'calc(100% - 30px - 40px - 2px - 21px)' }">
      <vxe-table show-overflow keep-source resizable ref="tableTestListRef" height="auto" :scroll-y="{ enabled: true }"
        :cell-style="cellClassName" :header-cell-style="{ height: '35px', padding: '0px 2px' }"
        :sort-config="{ iconAsc: 'vxe-icon-arrow-up', iconDesc: 'vxe-icon-arrow-down' }" :loading="loading"
        :data="labMainInfoList" :menu-config="rightMenuConfig" :keyboard-config="{ isArrow: true }"
        :row-config="{ height: wlRowHeight, isCurrent: true, isHover: true }"
        :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" @menu-click="contextMenuClickEvent"
        align="center" border @current-change="handleRowClick">
        <vxe-column width="16" fixed="left">
          <template #default="{ row }">
            <span style="width: 12px; height: 12px; display: inline-block; border-radius: 50%"
              :style="{ backgroundColor: row.mandatoryManualReview ? 'red' : row.autoVerification && row.autoVerificationManualReview ? '#fbbd08' : row.autoVerification && row.autoVerificationAutoReview ? '#39b54a' : '' }"></span>
          </template>
        </vxe-column>
        <vxe-column class-name="flag-cell" :field="colitem.fieldCode" :title="colitem.fieldName"
          :sortable="colitem.isSortable === 1" :fixed="colitem.isFix === 1 ? 'left' : ''"
          :align="!colitem.align ? 'left' : colitem.align" :header-align="!colitem.align ? 'left' : colitem.align"
          :width="colitem.columnWidth" v-for="(colitem, index) in testListColumns.filter((data) => data.isVisiable == 1)"
          :key="index">
          <template #header
            v-if="colitem.fieldCode === 'isUrgent' || colitem.fieldCode === 'isPrint' || colitem.fieldCode === 'isAutoPrint' || colitem.fieldCode === 'isChk' || colitem.fieldCode === 'isAlarm' || colitem.fieldCode === 'isResult'">
            <span v-if="colitem.fieldCode === 'isResult'" style="font-size: 300">
              <el-icon>
                <Select />
              </el-icon>
            </span>
            <span v-else style="font-size: 300">{{ colitem.fieldName }}</span>
          </template>
          <template #default="{ row }">
            <span v-if="colitem.fieldCode === 'isUrgent' && row.isUrgent === 1" class="el-icon-first-aid-kit">
              <el-icon>
                <WarnTriangleFilled />
              </el-icon>
            </span>
            <i v-else-if="colitem.fieldCode === 'isPrint' && row.isPrint === 1" class="el-icon-printer">
              <el-icon>
                <Printer />
              </el-icon>
            </i>
            <i v-else-if="colitem.fieldCode === 'isAutoPrint' && row.isAutoPrint === 1" class="el-icon-s-platform">
              <el-icon>
                <Monitor />
              </el-icon>
            </i>
            <i v-else-if="colitem.fieldCode === 'isChk' && row.isChk === 1" class="el-icon-s-check">
              <span style="color: #fff">初</span>
            </i>
            <i v-else-if="(colitem.fieldCode === 'isChk' && row.isChk === 2) || (colitem.fieldCode === 'isChk' && row.isChk === 1)"
              class="el-icon-finished">
              <el-icon>
                <SuccessFilled />
              </el-icon>
            </i>
            <el-tooltip v-if="colitem.fieldCode === 'criticalValueInfo' && row.criticalValueInfo" effect="dark"
              :content="row.criticalValueInfo" placement="top">
              <i class="el-icon-warning"></i>
            </el-tooltip>
            <i v-else-if="colitem.fieldCode === 'isAlarm' && row.isAlarm === 1" class="el-icon-warning">
              <el-icon>
                <WarningFilled />
              </el-icon>
            </i>
            <i v-else-if="colitem.fieldCode === 'isResult' && row.isResult === 1" class="el-icon-warning">
              <el-icon>
                <Select />
              </el-icon>
            </i>
            <span v-else-if="colitem.fieldCode === 'code'" :style="{ color: row.displayColor }">{{ row.code }}</span>
            <span v-else-if="colitem.fieldCode === 'specCode'" :style="{ color: row.displayColor }">{{ row.specCode
            }}</span>
            <span v-else-if="colitem.fieldCode === 'fullName'" :style="{ color: row.displayColor }">{{ row.fullName
            }}</span>
            <span v-else-if="colitem.fieldCode === 'medicalRecNo'" :style="{ color: row.displayColor }">{{
              row.medicalRecNo }}</span>
            <span v-else-if="colitem.fieldCode === 'visitTypeName'" :style="{ color: row.displayColor }">{{
              row.visitTypeName }}</span>
            <span v-else-if="colitem.fieldCode === 'abnormalFlag'" :style="{ color: 'red' }">{{ row.abnormalFlag }}</span>
            <div v-else-if="colitem.fieldCode === 'totalExistingResults'">
              <el-row>
                <el-col :span="12">
                  <div class="text-blue" style="text-align: right">
                    <span class="text-blue">{{ row.totalExistingResults }}</span>
                    <span style="font-size: 14px">/</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <span class="text-red" style="margin-left: 4px">{{ row.totalResults }}</span>
                </el-col>
              </el-row>
            </div>
            <span v-else-if="colitem.fieldCode === 'age'">{{ `${row[colitem.fieldCode] ? row[colitem.fieldCode] :
              ''}${row['ageUnit'] ? row['ageUnit'] : ''}${row['secAge'] ? row['secAge'] : ''}${row['secAgeUnit'] &&
                row['secAge'] ? row['secAgeUnit'] : ''}` }}</span>
            <span v-else>{{ colitem.fieldCode === 'isUrgent' || colitem.fieldCode === 'isPrint' || colitem.fieldCode ===
              'isAutoPrint' || colitem.fieldCode === 'isChk' || colitem.fieldCode === 'isAlarm' || colitem.fieldCode ===
              'isResult' ? '' :
              row[colitem.fieldCode] }}</span>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <vxe-toolbar class-name="bg-grey light footer-vxe-toolbar">
      <template #buttons>
        <span class="padding-lr-xs">定位</span>
        <vxe-input placeholder="请输入关键字" v-model="keyValueAnchor" @keydown="keyValueAnchorKeyDown"
          @change="keyValueAnchorChange" clearable />
        <span class="margin-left text-cut flex justify-start">
          <span class="padding-lr-xs text-bold">合计</span>
          <span class="text-blue">{{ testListStat.t }}</span>
          <span class="padding-lr-xs text-bold">已审</span>
          <span class="text-green">{{ testListStat.chkNum.length }}</span>
          <span class="padding-lr-xs text-bold">未审</span>
          <span class="text-grey">{{ testListStat.fChkNum.length }}</span>
          <!-- <span class="padding-lr-xs text-bold margin-left">状态</span>
          <span class="text-grey">100</span>
          <span class="padding-lr-xs text-bold  margin-left">收费</span>
          <span class="text-grey">100</span>
          <span class="padding-lr-xs text-bold  margin-left">金额</span>
          <span class="text-grey">100</span>
          <span class="padding-lr-xs text-bold  margin-left">检验者</span>
          <span class="text-grey">100</span>
          <span class="padding-lr-xs text-bold  margin-left">审核者</span>
          <span class="text-grey">100</span>-->
        </span>
      </template>
    </vxe-toolbar>
    <TestListEdit ref="testListEditRef" @uptSuccess="mainInfoUptSuccess" />
    <TestListBatchHandle ref="testListBatchHandleRef" @uptSuccess="mainInfoBatchUptSuccess" />
    <!-- 报告查询 -->
    <vxe-modal v-model="showRptSearch" v-if="showRptSearch" title="报告查询" destroy-on-close fullscreen :transfer="true"
      show-zoom resize>
      <template #default>
        <Reportsearch ref="rptSearchRef" />
      </template>
    </vxe-modal>

    <vxe-modal v-model="showCaSingData" title="CA签名" width="40vw" height="60vh" destroy-on-close :transfer="true"
      show-zoom resize>
      <div class="textareaBox">
        <el-form ref="indexConditionFormRef" :model="caForm" class="form-input-m" :inline-message="true">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item>
                <span class="textareaTitle">原始数据</span>
                <vxe-textarea :autosize="{ minRows: 3, maxRows: 3 }" v-model="caForm.caSignOri" class="textareaItem"
                  resize="vertical"></vxe-textarea>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item>
                <span class="textareaTitle">数据签名</span>
                <vxe-textarea :autosize="{ minRows: 2, maxRows: 2 }" v-model="caForm.caSignSec" class="textareaItem"
                  resize="vertical"></vxe-textarea>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item>
                <span class="textareaTitle">时间戳</span>
                <vxe-textarea :autosize="{ minRows: 11, maxRows: 14 }" v-model="caForm.caTimestamp" class="textareaItem"
                  resize="vertical"></vxe-textarea>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- </el-main>
            </el-container> -->
      </div>
    </vxe-modal>
    <vxe-modal v-model="showMainByReq" width="45vw" show-footer :mask="false">
      <template #title>
        <span class="text-bold">此条码上机记录</span>
      </template>
      <template #default>
        <div class="tableMoSaBox">
          <vxe-table ref="mainByReqNoTableRef" :data="labMainByReqNoList" class="mytable-scrollbar supplierTableClazz"
            border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }"
            :column-config="{ resizable: true }" resizable show-overflow keep-source
            :checkbox-config="{ checkMethod: checCheckboxkMethod2 }">
            <vxe-column type="checkbox" width="30" fixed="left" align="center"></vxe-column>
            <vxe-column type="seq" width="24" fixed="left"></vxe-column>
            <vxe-column class-name="flag-cell">
              <template #header>
                <span style="font-size: 300">审</span>
              </template>
              <template #default="{ row }">
                <i v-if="row.isChk === 1" class="el-icon-s-check">
                  <span style="color: #fff">初</span>
                </i>
                <i v-else-if="row.isChk === 2 || row.isChk === 1" class="el-icon-finished">
                  <el-icon>
                    <SuccessFilled />
                  </el-icon>
                </i>
              </template>
            </vxe-column>
            <vxe-column field="rptGroup" title="报告单元" width="90"></vxe-column>
            <vxe-column field="sampleda" title="检验日期" width="90"></vxe-column>
            <vxe-column field="sampleNo" title="标本号" width="90"></vxe-column>
            <vxe-column field="reqNo" title="条码号" min-width="120"></vxe-column>
            <vxe-column field="patNa" title="姓名" width="100"></vxe-column>
            <vxe-column field="reqPurpose" title="申请目的" width="100"></vxe-column>
            <vxe-column field="patNo" title="patNo" width="病历号" align="right"></vxe-column>
          </vxe-table>
        </div>
      </template>
      <template #footer>
        <vxe-button type="text" class="button-white margin-right" @click="cancelEqEvent">关闭</vxe-button>
        <vxe-button type="text" class="button-blue" @click="confirmCancelReqEvent">确定</vxe-button>
      </template>
    </vxe-modal>

  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, getCurrentInstance, onMounted, watch, provide, toRefs, computed } from 'vue';
import { VxeMessage, VxeNotifyType, VxeMessageMax } from '@/utils/CommonMessage';
import { formatDateTime, IsEmpty } from '@/utils/common';
import { stateOptions, testListRightMenus, mainInfoSort } from './TestListUtils.ts';
import { VXETable, VxeFormPropTypes, VxeFormInstance } from 'vxe-table';
import { LabMainInfoColumns } from '@/utils/LabMainInfoColumns';
import { clear } from 'xe-utils';
import { LabMainInfoFields } from '@/utils/LabMainInfoFields';
import { AppStore } from '@/stores/store';
import { BasicDicts } from '@/stores/basicdicts';
import { getOptionValueByCodeRptGroupOption, getOptionValueByCodeGlobalOption } from '@/utils/SysOptionsHelper';
import XEClipboard from 'xe-clipboard';
import { Splitpanes, Pane } from 'splitpanes';
import TestListEdit from './TestListEdit.vue'; /**编辑标本号窗体 */
import TestListBatchHandle from './TestListBatchHandle.vue'; /**批量操作窗体 */
import Reportsearch from '@/views/lab_sys/lab_set/Reportsearch.vue'; /**批量操作窗体 */

import security from '@/utils/securityPlugin.js';

const storeObj = AppStore();
const bdstoreObj = BasicDicts(); /**基础字典缓存对象 */
let { proxy }: any = getCurrentInstance();

//#region  Interface
interface PrimaryFormData {
  rptGroup: string;
  sampleda: string;
  sampleNo: string;
  reqNo: string;
}
//#endregion

//#region  属性
let props = defineProps({
  formObj: { type: Object as PropType<PrimaryFormData>, default: { rptGroup: '', sampleda: '', sampleNo: '', reqNo: '' } as PrimaryFormData }
});
//#endregion

//#region  计算属性
let testListStat = computed(() => {
  return { t: labMainInfoList.length, chkNum: labMainInfoList.filter((p) => p.isChk === 2), fChkNum: labMainInfoList.filter((p) => p.isChk === 0 || IsEmpty(p.isChk) || p.isChk === 1) };
});
let patTypeList = computed(() => {
  const a = Object.assign([], bdstoreObj.patTypeList);
  a.unshift({ code: null, name: '全部' });
  return a;
});

//#endregion

//#region  属性监听
watch(
  () => props.formObj,
  (n, o) => {
    //ToDo
  },
  { immediate: true, deep: true }
);
watch(
  () => storeObj.mergeTestListFinish,
  (n, o) => {
    //ToDo
    if (!IsEmpty(n)) {
      refreshMainInfoList();
    }
  },
  { immediate: true, deep: true }
);
//#endregion

const rightMenuConfig = ref(
  testListRightMenus(proxy, ({ options, column, row }) => {
    if (tableTestListRef.value) {
      tableTestListRef.value?.setCurrentRow(row);
      tableTestListRef.value?.focus();
      handleRowClick({ row });
    }
    const isDisabled = !column;
    options.forEach((list: any) => {
      list.forEach((item: any) => {
        item.disabled = isDisabled;
      });
    });
  })
);
const stateOpts = ref(stateOptions());
//const patTypeList = reactive(findLocalPatTypeListWithAll());
let state = ref(0);
let selPatType = ref(null);
let isSelfRpt = ref(0);
let labMainInfoList = reactive([]); //申请报告列表
let loading = ref(false);
let wlRowHeight = ref(24); //行高
let form = reactive({
  id: '',
  sampleda: '',
  sampleNo: '',
  reqNo: '',
  rptGroup: '',
  chkDoctor: '',
  testDoctor: ''
}) as any;

let caForm = reactive({
  caSignOri: '',
  caSignSec: '',
  caTimeStamp: ''
}) as any;


let maininfoform = reactive([]) as any;

let searchConditionObj = reactive({}) as any;
let testListColumns = reactive([]); /*检验列表列顺序*/
let isShowItemTemplatePanel = ref(false); /**是否显示项目模板面板 */
let showRptSearch = ref(false); /*报告查询面板 */
let showCaSingData = ref(false);
let showMainByReq = ref(false);
let tableTestListRef = ref(null);
let keyValueAnchor = ref(''); //锚点定位关键字
let anchorKeyDownCount = ref(0); //锚点定位执行回车的次数

const testListEditRef = ref(null); /**编辑检验记录 */
const testListBatchHandleRef = ref(null); /**批量操作组件对象 */
let rptSearchRef = ref(null); /**查看报告组件对象 */
// 方法定义区 =============
defineExpose({
  editMethod,
  testMethod,
  initPage,
  addMaininfo,
  baseInfoChange /*报告单元、检验日期、标本号、条码号改变后调用函数*/,
  updateMainInfoRow /*检验记录信息有变化，更新函数*/,
  refreshMainInfoListM2,
  refreshMainInfoListM3 /**授权成功后,更新检验记录 */,
  refreshMainInfoListM4 /**检验结果手动改变时调用 */,
  unChkMainInfo /** 取消审核*/,
  getCurrentRecordRow /** 获取当前选中行*/,
  nextRowSelected /**选中下一行操作 */,
  toggleItemTemplatePanel /**切换项目模板显示隐藏 */,
  getCurrentRecordList /**获取当前检验记录列表 */,
  getgetCurrentRecordListLength /**获取当前检验记录列表记录行数 */,
  isMultiFilterState /**判断当前是否处于条件筛选状态 */,
  findLabMainInfoByPrimaryData /**按报告单元，检验日期，标本号查询数据库有没有记录 */,
  waitSelectCurrentRow /**扫完条码不跳下一个标本号时等待选中当前标本号 */,
  getLabMainInfoTableList /**获取当前检验列表所有记录 */,
  wlRowHeight(res: any) {
    if (!IsEmpty(res)) {
      wlRowHeight.value = res;
    }
  }
});



/**获取检验记录列表 列顺序配置 */
function getFieldsConfigList(rptGroup: any) {
  testListColumns.length = 0;
  if (IsEmpty(rptGroup)) {
    testListColumns.push(...LabMainInfoColumns());
  } else {
    const url = '/lab/wlConfig/findWlConfigByRptGroup';
    const data = {
      suitModule: '1',
      rptGroup: rptGroup,
      type: 3
    };
    proxy.$http
      .get(url, { params: data })
      .then((res: any) => {
        testListColumns.length = 0;
        if (res.data.length > 0) {
          testListColumns.push(...res.data);
        } else {
          testListColumns.push(...LabMainInfoColumns());
        }
      })
      .catch((err: any) => {
        testListColumns.push(...LabMainInfoColumns());
      });
  }
}
/** 接收父组件传值 */
function initPage(repData: any) {
  if (IsEmpty(repData.rptGroup)) {
    return;
  }
  getFieldsConfigList(repData.rptGroup);
  if (repData !== null) {
    // for (let prop in repData) {
    //   form[prop] = repData[prop];
    // }
    Object.assign(form, repData);
  }

  findLabMaininfo(form);
  // proxy.$http
  //   // .post('/lab/maininfo/addMaininfo', form)
  //   .post('/lab/maininfo/insertMaininfoByReqNo')
  //   .then((res: any) => {
  //     findLabMaininfo(form);
  //   })
  //   .catch((err: any) => {
  //     VxeMessage('数据存储异常', VxeNotifyType.error);
  //   });
}

//保存上机记录
function testMethod(formData) {
  const url = '/lab/reqMain/insertMaininfo';
  const data = formData;
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (res && res.status && res.status.code !== 1) {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      } else if (res && res.status && res.status.code === 1) {
        appendMainInfoToList(res.data);
        //proxy.$emit('saveResult', res.data);
        //VxeMessage('保存成功', VxeNotifyType.success);
      } else {
        VxeMessage('请求错误', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('数据存储异常' + err, VxeNotifyType.error);
    });
}


//修改上机记录
function editMethod(formData) {
  //maininfoform.length = 0;
  const url = '/lab/reqMain/insertMaininfo';
  const data = formData;
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (res && res.status && res.status.code !== 1) {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      } else if (res && res.status && res.status.code === 1) {
        //maininfoform.push(res.data);
        //proxy.$emit('saveResult', maininfoform);
        const i = labMainInfoList.findIndex((p) => p.id === formData.id);
        if (i > -1) {
          Object.assign(labMainInfoList[i], res.data);
          handleRowClick({ row: labMainInfoList[i] });
        }
        //VxeMessage('保存成功', VxeNotifyType.success);
      } else {
        VxeMessage('请求错误', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('数据存储异常' + err, VxeNotifyType.error);
    });
}



/**查询当前选中记录是否审核
 */
function getCurrentRecordRow() {
  if (tableTestListRef.value) {
    const row = tableTestListRef.value?.getCurrentRecord();
    return row;
  }
  return null;
}
/**查询当前选中记录是否审核
 */
function getCurrentRecordList() {
  return labMainInfoList;
}
/**获取当前检验记录列表行数 */
function getgetCurrentRecordListLength() {
  return labMainInfoList.length;
}
/**跳转下一个标本
 * @param row 当前行
 * @param updown 【u】上一下【d】下一个
 */
function nextRowSelected(row, updown = 'd') {
  console.log('nextRowSelected', row, updown);

  if (tableTestListRef.value) {
    const ci = tableTestListRef.value?.getRowIndex(row);
    if (ci > -1) {
      const nci = updown === 'u' ? ci - 1 : ci + 1;
      if (nci >= 0 && nci <= labMainInfoList.length - 1) {
        const nrow = labMainInfoList[nci];
        tableTestListRef.value?.setCurrentRow(nrow);
        tableTestListRef.value?.focus();
        handleRowClick({ row: nrow });
      }
    }
  }
}
/**【没有上机记录的情况下】
 * 直接添加检验结果/或修改病人信息成功后
 * 刷新上机记录列表
 */
function refreshMainInfoListM2({ isSelCurRow, isRefreshRptResult, mainInfoId }) {
  /**如果是多条件查询，直接走这个 */
  if (isMultiFilterState()) {
    refreshMainInfoListM5(mainInfoId);
    return;
  }
  const url = '/lab/maininfo/findLabMaininfo';
  proxy.$http
    .get(url, { params: { rptGroup: form.rptGroup, sampleDaStr: form.sampleda } })
    .then((res: any) => {
      labMainInfoList.length = 0;
      labMainInfoList.push(...mainInfoSort(res.data));
      proxy.$emit('getLabMainInfoList', labMainInfoList);
      proxy.$forceUpdate();
      proxy.$nextTick(async () => {
        if (tableTestListRef.value) {
          await tableTestListRef.value?.reloadData(labMainInfoList);
          const rowNewi = labMainInfoList.findIndex((x) => x.id === mainInfoId);
          if (labMainInfoList.length > 0) {
            if (tableTestListRef.value) {
              handleRowClick({ row: labMainInfoList[rowNewi] }, isRefreshRptResult);
            }
          }
        }
      });
    })
    .catch((err: any) => {
      VxeMessage('搜索报告申请异常', VxeNotifyType.error);
    });
}
/**授权成功后,审核、更新检验记录
 * @e 更新条件
 */
async function refreshMainInfoListM3(e, isNextRow = true, isTreatPrint = true) {
  /**只修改当前标本 e.edtType===1*/
  /**修改所有未审核标本 e.edtType===2*/
  /**修改指定标本号范围 e.edtType===3*/
  proxy.$emit('IschkLoading', 1);
  let acterCode = '';
  let acterNa = '';
  switch (e.action) {
    case '1':
    case '2':
    case '4':
      acterCode = storeObj && storeObj.chkDoctorObj && !IsEmpty(storeObj.chkDoctorObj.code) ? storeObj.chkDoctorObj.code : '';
      acterNa = storeObj && storeObj.chkDoctorObj && !IsEmpty(storeObj.chkDoctorObj.name) ? storeObj.chkDoctorObj.name : '';
      break;
    case '3':
      acterCode = storeObj && storeObj.testDoctorObj && !IsEmpty(storeObj.testDoctorObj.code) ? storeObj.testDoctorObj.code : '';
      acterNa = storeObj && storeObj.testDoctorObj && !IsEmpty(storeObj.testDoctorObj.name) ? storeObj.testDoctorObj.name : '';
      break;
    default:
      break;
  }
  /**
   * 3731df09
   * 暂时注释罗相盛添加的代码   原因 审核时 提示 reqNo未定义
   * reqNo: reqNo,sampleNo: form.sampleNo,
   */
  //CA数据加密逻辑
  //获取系统参数
  let initData = '';
  let jmData = '';
  const a = getOptionValueByCodeGlobalOption('shsfkqcaqm');
  if (a && (a === '1' || a === 1)) {
    console.log('-----开始执行CA数据加密-----');
    let sdCertId = sessionStorage.getItem('sdCertId');
    if (sdCertId) {
      const url = '/lab/maininfo/getRptresultByLabMainInfo';
      await proxy.$http.get(url, { params: { rptGroup: form.rptGroup, sampleda: form.sampleda + ' 00:00:00', sampleNo: form.sampleNo } }).then((res: any) => {
        console.log(res.data);
        if (res.data.labMainInfo) {
          const data = res.data.labMainInfo;
          initData = data.patNo + '|' + data.patNa + '|' + data.sex + '|' + data.age + '|' + data.patType + '|' + data.reqPurpose + '|' + data.reqNo + '|' + data.sampleda + '|' + data.sampleNo + '|' + '结果：';
        }
        if (res.data.resultList && res.data.resultList.length > 0) {
          let resultData = '';
          res.data.resultList.forEach((element) => {
            resultData += element.itemNo;
            resultData += element.testResult;
          });
          initData = initData + resultData;
        }
      });
      console.log(initData);
      jmData = security.SOF_SignDataByP7(sdCertId, initData);
    }
  }
  const url = '/lab/maininfo/updateTestChkDoctorAfterAuth';
  proxy.$http
    .post(url, { sampleNo: form.sampleNo, rptGroup: form.rptGroup, sampleda: form.sampleda, id: form.id, edtType: e.edtType, codeRange: e.codeRange, action: e.action, acterCode: acterCode, acterNa: acterNa, caTpye: window.apiUrl.CA_TYPE, caUserId: storeObj.userInfo.caUserId, signDataId: storeObj.userInfo.signDataId, jmData: jmData, initData: initData })
    .then((res: any) => {
      //审核返回
      labMainInfoList.forEach((m, i) => {
        if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1 && res.data && res.data.curMainInfo && m.id === res.data.curMainInfo.id) {
          res.data.curMainInfo.sexNa = m.sexNa;
          res.data.curMainInfo.patTypeNa = m.patTypeNa;
          res.data.curMainInfo.reqDeptNa = m.reqDeptNa;
          res.data.curMainInfo.reqDoctorNa = m.reqDoctorNa;
          res.data.curMainInfo.sampleTypeNa = m.sampleTypeNa;
          res.data.curMainInfo.testDoctorNa = m.testDoctorNa;
          Object.assign(m, res.data.curMainInfo);

          if (labMainInfoList.length > 0) {
            /**判断审核后是否自动跳转下一个标本 【shtgzdxybb】*/
            const sysopt = getOptionValueByCodeRptGroupOption('shtgzdxybb');
            if (sysopt === '1' || sysopt === 1) {
              //跳转下一个标本
              const ii = i + 1;
              if (ii < labMainInfoList.length && isNextRow) {
                /**有下一个标本 */
                const nrow = Object.assign({}, labMainInfoList[ii]);
                tableTestListRef.value?.setCurrentRow(nrow);
                tableTestListRef.value?.focus();
                handleRowClick({ row: nrow });
              } else if (ii > labMainInfoList.length && isNextRow) {
                proxy.$emit('auditGetNextRow');
              }
              /**不跳转下一个标本 */
              if (!isNextRow || ii == labMainInfoList.length) {
                const nrow = Object.assign({}, labMainInfoList[i]);
                tableTestListRef.value?.setCurrentRow(nrow);
                tableTestListRef.value?.focus();
                handleRowClick({ row: nrow });
              }
            }

            //静默更新其他修改项
            if (sysopt !== '1' && sysopt !== 1) {
              if (tableTestListRef.value) {
                tableTestListRef.value?.setCurrentRow(m);
                tableTestListRef.value?.focus();
                handleRowClick({ row: m });
              }
            }
          }
        }
        if (res && res.data && res.data.uptedLabMainInfos && res.data.uptedLabMainInfos.length > 0) {
          const am = res.data.uptedLabMainInfos.filter((p) => p.id === m.id);
          if (am && am.length > 0) {
            Object.assign(m, am[0]);
          }
        }
      });
      /**审核后自动打印 */
      if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1 && res.data && res.data.curMainInfo) {
        const rptopt = getOptionValueByCodeRptGroupOption('shhzddy');
        if ((rptopt === '1' || rptopt === 1) && isTreatPrint) {
          proxy.$emit('printAfterChk', res.data.curMainInfo);
        }
      }

      if (res && res.status && !IsEmpty(res.status.code) && res.status.code !== 1 && !IsEmpty(res.status.msg)) {
        VxeMessage(`${res.status.msg}`, VxeNotifyType.error);
      }
      proxy.$emit('IschkLoading', 2);
    })
    .catch((err: any) => {
      proxy.$emit('IschkLoading', 2);
      VxeMessage('数据请求失败', VxeNotifyType.error);
    });
}
/**只刷新记录信息，不做行选中操作，因为中间结果 处理时 已经选中本行数据 【中间结果改变时会用到】
 * @param mainInfoId 检验记录主键
 */
function refreshMainInfoListM4(mainInfoId) {
  const url = '/lab/maininfo/findLabMaininfo';
  proxy.$http
    .get(url, { params: { id: mainInfoId, rptGroup: form.rptGroup, sampleDaStr: form.sampleda } })
    .then((res: any) => {
      if (res && res.data && res.data.length > 0) {
        let ci = labMainInfoList.findIndex((p) => p.id === mainInfoId);
        if (ci > -1) {
          Object.assign(labMainInfoList[ci], res.data[0]);
          proxy.$emit('tipsAlarmExist');
        }
      }
    })
    .catch((err: any) => {
      VxeMessage('搜索报告申请异常', VxeNotifyType.error);
    });
}
/**如果是多条件查询状态下,新增标本，如果符合多条件则更新列表，如果不符合多条件，则之刷新人员信息跟中间结果 */
function refreshMainInfoListM5(mainInfoId) {
  if (!isMultiFilterState()) {
    return;
  }
  let paramData = { rptGroup: form.rptGroup, sampleDaStr: form.sampleda } as any;
  if (state.value !== 0) {
    paramData.stateCode = state.value;
  }
  if (isSelfRpt.value === 1) {
    paramData.isSelf = isSelfRpt.value;
  }
  if (selPatType.value !== null) {
    paramData.patType = selPatType.value;
  }

  const url = '/lab/maininfo/findLabMaininfo';
  proxy.$http
    .get(url, { params: paramData })
    .then(async (res) => {
      if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1 && res.data && res.data.length > 0) {
        const i = res.data.findIndex((p) => p.id === mainInfoId);
        const ii = labMainInfoList.findIndex((p) => p.id === mainInfoId);
        if (i > -1) {
          //列表中已有,更新本条检验记录
          if (ii > -1) {
            const nrow = Object.assign(labMainInfoList[ii], res.data[i]);
            tableTestListRef.value?.setCurrentRow(nrow);
            tableTestListRef.value?.focus();
            handleRowClick({ row: nrow });
          } else {
            //列表中没有
            labMainInfoList.push(res.data[i]);
            await tableTestListRef.value?.reloadData(labMainInfoList);
            tableTestListRef.value?.setCurrentRow(res.data[i]);
            tableTestListRef.value?.focus();
            handleRowClick({ row: res.data[i] });
          }
        } else {
          //回调，更新病人信息，检验结果等,重新查询本条记录
          const _rows = await findLabMainInfoByPrimaryData(form.rptGroup, form.sampleda, form.sampleNo, mainInfoId);
          if (_rows && _rows.length > 0) {
            //form.id = _rows[0].id;
            proxy.$emit('onlyUpdatePatResultInfo', _rows[0]);
          }
          //
        }
      }
    })
    .catch((err) => { });
}

/**如果是多条件筛选状态下，上机，清空筛选条件后刷新列表不做选中操作 */
function refreshMainInfoListM6(callback) {
  loading.value = true;
  const url = '/lab/maininfo/findLabMaininfo';
  let paramData = { rptGroup: form.rptGroup, sampleDaStr: form.sampleda } as any;
  proxy.$http
    .get(url, { params: paramData })
    .then((res: any) => {
      labMainInfoList.length = 0;
      labMainInfoList.push(...mainInfoSort(res.data));
      if (callback) {
        callback();
      }
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('搜索报告申请异常', VxeNotifyType.error);
    });
}

/**扫完条码不跳下一个标本号时等待选中当前标本号 */
function waitSelectCurrentRow(formDataObj, value, isMulti) {
  const index = labMainInfoList.findIndex((p) => {
    return p.sampleda === formDataObj.sampleda && p.reqNo === `${value}`;
  });
  if (index <= -1 && (isMulti === null || isMulti < 200)) {
    setTimeout(() => {
      waitSelectCurrentRow(formDataObj, value, IsEmpty(isMulti) ? 2 : isMulti + 1);
    }, 100);
    return;
  }
  handleRowClick({ row: labMainInfoList[index] });
}

/**取消审核记录
 * @e 1,取消初审  2 取消审核
 */
function unChkMainInfo(e, authUser: any) {
  let ar = tableTestListRef.value?.getCurrentRecord();
  if (!IsEmpty(e.unChkDoctor)) {
    const a = 'isIncintoQi';
    const b = 'unChkDoctor';
    const b1 = 'unChkDoctorNa';
    const c = 'unchkTime';
    const d = 'unchkReason';
    const g = 'cancleAuditList';
    ar[a] = e[a];
    ar[b] = e[b];
    ar[b1] = e[b1];
    ar[c] = e[c];
    ar[d] = e[d];
    ar[g] = e[g];
  }
  if (authUser) {
    ar.unChkDoctor = IsEmpty(authUser.code) ? '' : authUser.code;
    ar.unChkDoctorNa = IsEmpty(authUser.name) ? '' : authUser.name;
  }

  const a = getOptionValueByCodeGlobalOption('xsczrxyzdl'); /**消审操作人需再登录 xsczrxyzdl*/
  if (a && (a === '1' || a === 1)) {
    if (ar.unChkDoctor != ar.chkDoctor) {
      VxeMessage('取消审核检验失败,消审人和审核人不一致', VxeNotifyType.error);
      return;
    }
  }
  const url = '/lab/maininfo/unChkMainInfo';
  proxy.$http
    .post(url, ar)
    .then((res: any) => {
      //审核返回
      if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1 && res.data) {
        const am = labMainInfoList.findIndex((p) => p.id === res.data.id);
        if (am > -1) {
          Object.assign(labMainInfoList[am], res.data);
          if (labMainInfoList.length > 0) {
            if (tableTestListRef.value) {
              tableTestListRef.value?.setCurrentRow(labMainInfoList[am]);
              tableTestListRef.value?.focus();
              const _row = Object.assign({}, labMainInfoList[am]);
              handleRowClick({ row: _row });
            }
          }
        }
      } else if (res && res.status && !IsEmpty(res.status.code) && res.status.code !== 1) {
        VxeMessage(res.status.msg ? res.status.msg : '取消审核检验失败,请联系管理员', VxeNotifyType.error);
      } else if (res && res.status && !IsEmpty(res.status) && res.status === 500) {
        VxeMessage(res.message ? res.message : '取消审核检验失败,请联系管理员', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      if (res && res.status && !IsEmpty(res.status) && res.status === 500) {
        VxeMessage(res.message ? res.message : '取消审核检验失败,请联系管理员', VxeNotifyType.error);
      } else {
        VxeMessage('取消检验失败', VxeNotifyType.error);
      }
    });
}
/**删除上机记录
 */
async function deleteMainInfo() {
  const ar = tableTestListRef.value?.getCurrentRecord();
  if (!ar || IsEmpty(ar) || IsEmpty(ar.sampleda)) {
    VxeMessage('请选中要删除的记录', VxeNotifyType.warning);
    return;
  }
  if (ar.isChk === 1) {
    VxeMessage('已初审,不允许删除', VxeNotifyType.warning);
    return;
  }
  if (ar.isChk === 2) {
    VxeMessage('已审核,不允许删除', VxeNotifyType.warning);
    return;
  }
  const type = await VXETable.modal.confirm('确定删除选中记录?'); /*不能改el  $confirm 回车事件冒泡你*/
  if (type === 'confirm') {
    const url = `/lab/maininfo/deleteMaininfoById`;
    let params = {
      id: ar.id,
      sampleda: ar.sampleda,
      rptGroup: ar.rptGroup,
      sampleNo: ar.sampleNo
    };
    proxy.$http
      .post(url, params)
      .then(async (res: any) => {
        //审核返回
        if (res && res.status && res.status.code && !IsEmpty(res.status.code) && res.status.code === 1) {
          const ci = tableTestListRef.value?.getRowIndex(ar);
          await tableTestListRef.value?.remove(ar);
          labMainInfoList.splice(ci, 1);
          if (ci <= labMainInfoList.length - 1) {
            tableTestListRef.value?.setCurrentRow(labMainInfoList[ci]);
            tableTestListRef.value?.focus();
            const _row = Object.assign({}, labMainInfoList[ci]);
            handleRowClick({ row: _row });
          } else {
            handleRowClick({ row: labMainInfoList.length > 0 ? labMainInfoList[labMainInfoList.length - 1] : null });
          }
        }
      })
      .catch((err: any) => {
        VxeMessage('取消检验失败', VxeNotifyType.error);
      });
  }
}
/**刷新检验记录
 */
function refreshMainInfoList() {
  let condition = {} as any;
  if (state.value !== 0) {
    condition.stateCode = state.value;
  }
  if (isSelfRpt.value === 1) {
    condition.isSelf = 1;
  }
  if (selPatType.value !== null) {
    condition.patType = selPatType.value;
  }
  findLabMaininfo(
    condition,
    () => {
      /**刷新样本时提示危急值 sxybstswjz*/
      const a = getOptionValueByCodeGlobalOption('sxybstswjz');
      if (a && (a === '1' || a === 1)) {
        proxy.$emit('tipsAlarmExist');
      }
    },
    IsEmpty(condition) ? false : true
  );
}



/**添加上机记录 */
async function addMaininfo(reqData: any, callback) {
  console.log('======================================');

  if (IsEmpty(reqData.rptGroup) || IsEmpty(reqData.sampleda) || IsEmpty(reqData.sampleNo)) {
    return;
  }
  if (reqData !== null) {
    // for (let prop in reqData) {
    //   form[prop] = reqData[prop];
    // }
    Object.assign(form, reqData);
  }

  /**记忆上机人 审核人添加到 form */
  //#region 默认添加记忆的检验者  审核者
  let approveConfirmObj = {} as any;
  try {
    const approveConfirm = sessionStorage.getItem('locChkDoctor');
    if (IsEmpty(approveConfirm)) {
      //todo
    } else {
      approveConfirmObj = JSON.parse(approveConfirm);
      //验证是否过期
      const curDateTime = new Date().valueOf();
      if (Number(curDateTime) <= Number(approveConfirmObj.expressin)) {
        const a = 'chkDoctor';
        form[a] = approveConfirmObj.code;
      }
    }
  } catch (error) {
    //todo
  }
  try {
    const approveConfirm = sessionStorage.getItem('locTestDoctor');
    if (IsEmpty(approveConfirm)) {
      /**没有记忆，取当前登陆人的code  name */
      const locRemObj = localStorage.getItem('userInfo');
      if (!IsEmpty(locRemObj)) {
        const locRemObjEntry = JSON.parse(locRemObj);
        if (!IsEmpty(locRemObjEntry.username)) {
          form.testDoctor = locRemObjEntry.username;
        }
        if (!IsEmpty(locRemObjEntry.realname)) {
          form.testDoctorNa = locRemObjEntry.realname;
        }
      }
    } else {
      approveConfirmObj = JSON.parse(approveConfirm);
      //验证是否过期
      const curDateTime = new Date().valueOf();
      if (Number(curDateTime) <= Number(approveConfirmObj.expressin)) {
        const a = 'testDoctor';
        form[a] = approveConfirmObj.code;
      }
    }
  } catch (error) {
    //todo
  }
  //@endregion
  const formSaveObj = Object.assign({}, form);
  /**保存前验证是否已经存在该标本号的数据，防止同一个标本号在多台电脑扫码重复的问题 */
  const jgObjs = await validateIsExistMainInfo(form);
  const jgObj = jgObjs && jgObjs.length > 0 ? jgObjs[0] : null;
  if (jgObj && !IsEmpty(jgObj.patNa) && !IsEmpty(jgObj.reqNo)) {
    const type = await VXETable.modal.confirm(`该标本号已上机\n姓名: ${jgObj.patNa}\n条码号: ${jgObj.reqNo}\n上机时间: ${jgObj.createTime}\n上机人: ${jgObj.testDoctorNa}\n是否继续?`); /*不能改el  $confirm 回车事件冒泡你*/
    if (type === 'confirm') {
      //todo
    } else {
      //todo
      return;
    }
  }
  maininfoform.length = 0;
  proxy.$http
    .post('/lab/reqMain/insertMaininfoByReqNo', formSaveObj)
    .then((res: any) => {
      if (res && res.status && res.status.code !== 1) {
        VxeMessageMax(res.status.msg, VxeNotifyType.error);
      } else if (res && res.status && res.status.code === 1) {
        maininfoform.push(res.data);
        appendMainInfoToList(res.data);
        //向父组件传值
        proxy.$emit('mainInfoRowChangeV2', maininfoform);

        if (callback) {
          callback(res.data);
        }
      } else {
        VxeMessage('请求错误', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('数据存储异常', VxeNotifyType.error);
    });
}

/**验证标本号是否已经创建 */
function validateIsExistMainInfo(labmaininfo) {
  return new Promise((resolve, reject) => {
    const url = '/lab/maininfo/validateIsExistMainInfo';
    proxy.$http
      .get(url, { params: { sampleNo: labmaininfo.sampleNo, rptGroup: labmaininfo.rptGroup, sampleDaStr: labmaininfo.sampleda } })
      .then((res: any) => {
        if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1 && res.data && res.data.length > 0) {
          resolve(res.data);
        } else {
          resolve(null);
        }
      })
      .catch((err: any) => {
        resolve(null);
      });
  });
}

/**更新上机记录 */
function updateMaininfo(row, reqNo) {
  let data = {
    rptGroup: row.rptGroup,
    sampleNo: row.sampleNo,
    sampleda: row.sampleda,
    reqNo: row.reqNo === reqNo || IsEmpty(reqNo) ? null : reqNo,
    labMaininfo: row
  };
  proxy.$http
    .post('/lab/maininfo/updateMaininfo', data)
    .then((res: any) => {
      if (res && res.status && res.status.code !== 1) {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      } else if (res && res.status && res.status.code === 1) {
        const i = labMainInfoList.findIndex((p) => p.id === row.id);
        if (i > -1) {
          Object.assign(labMainInfoList[i], res.data);
        } else {
          Object.assign(row, res.data);
        }
        proxy.$emit('quietRefreshRptresult');
      } else {
        VxeMessage('请求错误', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('更新检验记录失败,请联系管理员', VxeNotifyType.error);
    });
}
/**扫条码更新上机记录 */
function updateMaininfoByScanReqNo(row, reqNo) {
  let data = {
    rptGroup: row.rptGroup,
    sampleNo: row.sampleNo,
    sampleda: row.sampleda,
    reqNo: reqNo,
    labMaininfo: row
  };
  proxy.$http
    .post('/lab/maininfo/updateMaininfoByScanReqNo', data)
    .then(async (res: any) => {
      if (res && res.status && res.status.code !== 1) {
        if (res && res.status && res.status.code === 400) {
          //res.status.msg
          const type = await VXETable.modal.confirm({ status: 'error', content: res.status.msg });
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      } else if (res && res.status && res.status.code === 1) {
        const i = labMainInfoList.findIndex((p) => p.id === row.id);
        if (i > -1) {
          Object.assign(labMainInfoList[i], res.data);
          handleRowClick({ row: labMainInfoList[i] });
        } else {
          Object.assign(row, res.data);
        }
      } else {
        VxeMessage('请求错误', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('更新检验记录失败,请联系管理员', VxeNotifyType.error);
    });
}
/**单元格样式
 *【1】是否启用系统选项颜色配置  encolorsetting
 *【1】急背景色  isurgentcolor
 *【2】打背景色  isprintcolor
 *【3】自助机打印背景色  isautoprintcolor
 *【4】审核背景色  ischkcolor
 *【5】危急值背景色  isalarmcolor
 *【6】门诊类型病人列表颜色  mzpattypecolor
 *【7】住院类型病人列表颜色  zypattypecolor
 *【8】急诊类型病人列表颜色  jzpattypecolor
 *【9】体检类型病人列表颜色  tjpattypecolor
 *【10】其他类型病人列表颜色  qtpattypecolor
 */
function cellClassName({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  let patTypeColor = '';
  if (column && !IsEmpty(column.fixed)) {
    const a = getOptionValueByCodeGlobalOption('encolorsetting');
    if (a === '1' || a === 1) {
      if (row && row.patType === '1') {
        //门诊
        const b = getOptionValueByCodeGlobalOption('mzpattypecolor');
        if (!IsEmpty(b)) {
          patTypeColor = b;
        }
      } else if (row && row.patType === '2') {
        //急诊
        const b = getOptionValueByCodeGlobalOption('jzpattypecolor');
        if (!IsEmpty(b)) {
          patTypeColor = b;
        }
      } else if (row && row.patType === '3') {
        //住院
        const b = getOptionValueByCodeGlobalOption('zypattypecolor');
        if (!IsEmpty(b)) {
          patTypeColor = b;
        }
      } else if (row && row.patType === '4') {
        //体检
        const b = getOptionValueByCodeGlobalOption('tjpattypecolor');
        if (!IsEmpty(b)) {
          patTypeColor = b;
        }
      } else {
        //其他
        if (!IsEmpty(row.patType)) {
          const b = getOptionValueByCodeGlobalOption('qtpattypecolor');
          if (!IsEmpty(b)) {
            patTypeColor = b;
          }
        }
      }
    }
  }
  if (column.property === 'isUrgent') {
    if (row.isUrgent === 1) {
      const a = getOptionValueByCodeGlobalOption('encolorsetting');
      const b = getOptionValueByCodeGlobalOption('isurgentcolor');
      if (a === 1 || a === '1') {
        if (!IsEmpty(b)) {
          return { background: b, color: '#fff', padding: '0', margin: '0' };
        }
      }
      return { background: '#FF0000', color: '#fff' };
    } else {
      return !IsEmpty(patTypeColor) ? { color: patTypeColor } : {};
    }
  }
  if (column.property === 'isChk') {
    if (row.isChk === 2) {
      const a = getOptionValueByCodeGlobalOption('encolorsetting');
      const b = getOptionValueByCodeGlobalOption('ischkcolor');
      if (a === 1 || a === '1') {
        if (!IsEmpty(b)) {
          return { background: b, color: '#fff' };
        }
      }
      return { background: '#008000', color: '#fff' };
    } else if (row.isChk === 1) {
      const a = getOptionValueByCodeGlobalOption('encolorsetting');
      const b = getOptionValueByCodeGlobalOption('ischkcolor');
      if (a === 1 || a === '1') {
        if (!IsEmpty(b)) {
          return { background: b, color: '#fff' };
        }
      }
      return { background: '#00FF00', color: '#fff' };
    } else {
      return !IsEmpty(patTypeColor) ? { color: patTypeColor } : {};
    }
  }
  if (column.property === 'isAlarm') {
    if (row.isAlarm === 1) {
      const a = getOptionValueByCodeGlobalOption('encolorsetting');
      const b = getOptionValueByCodeGlobalOption('isalarmcolor');
      if (a === 1 || a === '1') {
        if (!IsEmpty(b)) {
          return { background: b, color: '#fff' };
        }
      }
      return { background: '#FF9900', color: '#fff' };
    } else {
      return !IsEmpty(patTypeColor) ? { color: patTypeColor } : {};
    }
  }
  if (column.property === 'isResult') {
    if (row.isResult === 1) {
      const a = getOptionValueByCodeGlobalOption('encolorsetting');
      const b = getOptionValueByCodeGlobalOption('isResultColor');
      if (a === 1 || a === '1') {
        if (!IsEmpty(b)) {
          return { background: b, color: '#fff' };
        }
      }
      //return { background: '#14DC14', color: '#fff' };
    } else {
      return !IsEmpty(patTypeColor) ? { color: patTypeColor } : {};
    }
  }
  if (column.property === 'isAutoPrint') {
    if (row.isAutoPrint === 1) {
      const a = getOptionValueByCodeGlobalOption('encolorsetting');
      const b = getOptionValueByCodeGlobalOption('isautoprintcolor');
      if (a === 1 || a === '1') {
        if (!IsEmpty(b)) {
          return { background: b, color: '#fff' };
        }
      }
      return { background: '#800080', color: '#fff' };
    } else {
      return !IsEmpty(patTypeColor) ? { color: patTypeColor } : {};
    }
  }
  if (column.property === 'isPrint') {
    if (row.isPrint === 1) {
      const a = getOptionValueByCodeGlobalOption('encolorsetting');
      const b = getOptionValueByCodeGlobalOption('isprintcolor');
      if (a === 1 || a === '1') {
        if (!IsEmpty(b)) {
          return { background: b, color: '#fff' };
        }
      }
      return { background: '#000080', color: '#fff' };
    } else {
      return !IsEmpty(patTypeColor) ? { color: patTypeColor } : {};
    }
  }
  return !IsEmpty(patTypeColor) ? { color: patTypeColor } : {};
}
/**上机记录添加成功，列表中最后一条补一条
 * @row 新增的检验记录
 */
function appendMainInfoToList(row) {
  labMainInfoList.push({ ...row });
  labMainInfoList = mainInfoSort(labMainInfoList);
  if (tableTestListRef.value) {
    proxy.$nextTick(() => {
      setTimeout(async () => {
        await tableTestListRef.value?.scrollToRow(labMainInfoList[labMainInfoList.length - 1]);
      }, 500);
    });
  }

  // handleRowClickV2({ row });
}
/**筛选条件发生改变 */
function conditionSelectChange() {
  let condition = { stateCode: state.value } as any;
  if (isSelfRpt.value === 1) {
    condition.isSelf = 1;
  }
  if (selPatType.value !== null) {
    condition.patType = selPatType.value;
  }
  findLabMaininfo(condition, null, true);
}
/**查询全部 */
function searchAll() {
  state.value = 0;
  isSelfRpt.value = 0;
  selPatType.value = null;
  conditionSelectChange();
}
/**获取报告申请
 * @form rptGroup,sampleda,sampleNo,reqNo 参数实体
 * @callback 请求数据成功后的回调函数
 **/
function findLabMaininfo(mainInfo, callback, isMultiConditions = false) {
  loading.value = true;
  labMainInfoList.length = 0;
  const url = '/lab/maininfo/findLabMaininfo';
  let paramData = { rptGroup: form.rptGroup, sampleDaStr: form.sampleda } as any;
  if (isMultiConditions) {
    if (mainInfo && !IsEmpty(mainInfo.stateCode)) {
      paramData.stateCode = mainInfo.stateCode;
    }
    if (mainInfo && !IsEmpty(mainInfo.isSelf)) {
      paramData.isSelf = mainInfo.isSelf;
    }
    if (mainInfo && !IsEmpty(mainInfo.patType)) {
      paramData.patType = mainInfo.patType;
    }
  }
  proxy.$http
    .get(url, { params: paramData })
    .then((res: any) => {
      labMainInfoList.push(...mainInfoSort(res.data));
      proxy.$emit('getLabMainInfoList', labMainInfoList);
      if (callback) {
        callback();
      }
      if (labMainInfoList.length > 0) {
        const $table = proxy.$refs.tableTestListRef as any;
        if ($table) {
          let selectList = labMainInfoList.find((item) => item.sampleNo === form.sampleNo);

          /**刷新后自动跳到____标本号 sxhtzdbbh */
          const a = getOptionValueByCodeRptGroupOption('sxhtzdbbh');

          /**刷新后跳到【最前】标本 */
          if (!IsEmpty(a) && (a === '0' || a === 0)) {
            selectList = labMainInfoList[0];
          }
          /**刷新后跳到【最后】标本*/
          if (!IsEmpty(a) && (a === '2' || a === 2)) {
            selectList = labMainInfoList[labMainInfoList.length - 1];
          }

          if (selectList === undefined && !isMultiConditions /*非多条件查询*/) {
            loading.value = false;
            form.id = '';
            proxy.$emit('getReqRptResult', form);
            return;
          }

          if (selectList === undefined && isMultiConditions /*多条件查询*/) {
            selectList = labMainInfoList[0];
          }

          $table.setCurrentRow(selectList);
          $table.focus();
          handleRowClick({ row: selectList });
          proxy.$emit('tipsAlarmExist');
        }
      } else {
        proxy.$emit('mainInfoRowChange', null);
      }
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('搜索报告申请异常' + err, VxeNotifyType.error);
    });
}
/**获取检验列表当前所有记录 */
function getLabMainInfoTableList() {
  return labMainInfoList;
}
/**按报告单元，检验日期，标本号查询数据库有没有记录 */
function findLabMainInfoByPrimaryData(rptGrpId, sampleda, sampleno, id = '') {
  return new Promise((resolve, reject) => {
    const url = '/lab/maininfo/findLabMaininfo';
    proxy.$http
      .get(url, { params: { rptGroup: rptGrpId, sampleDaStr: sampleda, sampleNo: sampleno, id: id } })
      .then((res: any) => {
        if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1 && res.data && res.data.length > 0) {
          resolve(res.data);
        } else {
          resolve(null);
        }
      })
      .catch((err: any) => {
        resolve(null);
      });
  });
}
/**按条码号没有记录 */
function findLabMainInfoByReqNo(rptGroup, reqNo) {
  return new Promise((resolve, reject) => {
    const url = '/lab/maininfo/findLabMaininfoByReqNo';
    proxy.$http
      .get(url, { params: { reqNo: reqNo, rptGroup: rptGroup } })
      .then((res: any) => {
        if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1 && res.data && res.data.length > 0) {
          resolve(res.data);
        } else {
          resolve(null);
        }
      })
      .catch((err: any) => {
        resolve(null);
      });
  });
}


// /**行点击事件 */
// function handleRowClickV2({ row }: any, isRefreshRptResult) {
//   if (row) {
//     form.id = IsEmpty(row.id) ? '' : row.id;
//     form.sampleNo = row.sampleNo;
//     form.rptGroup = row.rptGroup;
//     form.reqNo = row.reqNo;
//     form.sampleda = row.sampleda;
//     form.orgId = row.orgId;
//     proxy.$nextTick(() => {
//       if (tableTestListRef.value) {
//         setTimeout(async () => {
//           await tableTestListRef.value?.setCurrentRow(row);
//           await tableTestListRef.value?.scrollToRow(row);
//           tableTestListRef.value?.focus();
//         }, 50);
//       }
//       proxy.$emit('mainInfoRowChange', maininfoform);
//       //proxy.$emit('mainInfoRowChange', row, isRefreshRptResult);
//     });
//   } else {
//     proxy.$emit('mainInfoRowChange', maininfoform);
//     //proxy.$emit('mainInfoRowChange', row, isRefreshRptResult);
//   }
//   // console.log('handleRowClickV2',maininfoform);
//   proxy.$emit('mainInfoRowChangeV2', maininfoform);

// }


/**行点击事件 */
function handleRowClick({ row }: any, isRefreshRptResult) {
  if (row) {
    form.id = IsEmpty(row.id) ? '' : row.id;
    form.sampleNo = row.sampleNo;
    form.rptGroup = row.rptGroup;
    form.reqNo = row.reqNo;
    form.sampleda = row.sampleda;
    form.orgId = row.orgId;
    proxy.$nextTick(() => {
      if (tableTestListRef.value) {
        setTimeout(async () => {
          await tableTestListRef.value?.setCurrentRow(row);
          await tableTestListRef.value?.scrollToRow(row);
          tableTestListRef.value?.focus();
        }, 50);
      }
      proxy.$emit('mainInfoRowChange', row, isRefreshRptResult);
    });
  } else {
    proxy.$emit('mainInfoRowChange', row, isRefreshRptResult);
  }
}
/**检验记录有信息变化，同步信息处理 */
function updateMainInfoRow(row) {
  if (IsEmpty(row)) {
    return;
  }
  const index = labMainInfoList.findIndex((p) => {
    return p.id === row.id;
  });
  if (index > -1) {
    Object.assign(labMainInfoList[index], row);
  } else {
    refreshMainInfoListM2({ isSelCurRow: true, isRefreshRptResult: true, mainInfoId: row.id });
  }
  proxy.$forceUpdate();
}
/**编辑右侧病人信息
 * @type 发生改变的值
 * →【1】报告单元值变化;
 * →【2】检验日期值发生变化
 * →【3】标本号值发生变化
 * →【4】条码号值发生变化
 * @value 发生变化后的值
 * @formDataObj form对象所有值
 */
async function baseInfoChange(type, value, formDataObj, callback) {
  if (IsEmpty(type)) {
    return;
  }
  switch (type) {
    case 1:
      console.log('走的1', type, value, formDataObj);
      break;
    case 2:
      console.log('走的2', type, value, formDataObj);
      break;
    case 3:
      const index = labMainInfoList.findIndex((p) => {
        return p.sampleda === formDataObj.sampleda && p.sampleNo === `${value}`;
      });
      if (index > -1) {
        handleRowClick({ row: labMainInfoList[index] });
      } else {
        tableTestListRef.value?.setCurrentRow({});
        tableTestListRef.value?.scrollToRow(labMainInfoList[labMainInfoList.length - 1]);
        proxy.$emit('mainInfoRowChange', null);
        //proxy.$emit('getReqRptResult', null);
      }
      if (callback) {
        callback();
      }
      break;
    case 4:
      /**扫码上机不清除筛选条件 smsjbqcsxtj */
      const a = getOptionValueByCodeRptGroupOption('smsjbqcsxtj');
      let smsjbqcsxtj = false;
      if (!IsEmpty(a) && (a === '1' || a === 1)) {
        smsjbqcsxtj = true;
      } else {
        smsjbqcsxtj = false;
      }

      if (IsEmpty(value)) {
        //先检索列表中有没有该条码号
        const index = labMainInfoList.findIndex((p) => {
          return p.sampleda === formDataObj.sampleda && p.rptGroup === `${formDataObj.rptGroup}` && p.sampleNo === `${formDataObj.sampleNo}`;
        });
        if (index > -1) {
          //有：选中
          const rowObj = labMainInfoList[index];
          handleRowClick({ row: rowObj });
          if (rowObj && IsEmpty(rowObj.reqNo)) {

            updateMaininfo(rowObj, value);
            if (callback) {
              callback();
            }
          }
        } else {
          form.id = '';
          form.reqNo = value;
          form.rptGroup = formDataObj.rptGroup;
          form.sampleNo = formDataObj.sampleNo;
          form.sampleda = formDataObj.sampleda;
          if (!isMultiFilterState()) {
            //#region  保存前验证是否已经存在该标本号的数据，防止同一个标本号在多台电脑扫码重复的问题

            const jgObjs = await validateIsExistMainInfo(form);
            const jgObj = jgObjs && jgObjs.length > 0 ? jgObjs[0] : null;
            if (jgObj && !IsEmpty(jgObj.patNa) && !IsEmpty(jgObj.reqNo)) {
              const type = await VXETable.modal.confirm(`该标本号已上机\n姓名: ${jgObj.patNa}\n条码号: ${jgObj.reqNo}\n上机时间: ${jgObj.createTime}\n上机人: ${jgObj.testDoctorNa}\n是否继续?`); /*不能改el  $confirm 回车事件冒泡你*/
              if (type === 'confirm') {
                //todo
              } else {
                //todo
                return;
              }
            }

            //#endregion

            proxy.$emit('addMaininfo', formDataObj);
            //addMaininfo(formDataObj);
            if (callback) {
              callback();
            }
          }
          if (isMultiFilterState()) {
            if (!smsjbqcsxtj) {
              //先查询数据库有没有
              const isHasRow = await findLabMainInfoByPrimaryData(form.rptGroup, form.sampleda, form.sampleNo);
              //有，则刷新病人信息，结果列表
              if (isHasRow && isHasRow.length > 0) {
                proxy.$emit('onlyUpdatePatResultInfo', isHasRow[0]);
              }
              //无，则创建
              if (!isHasRow || isHasRow.length <= 0) {
                //先清空条件筛选
                state.value = 0;
                isSelfRpt.value = 0;
                selPatType.value = null;
                let condition = { stateCode: state.value } as any;
                if (isSelfRpt.value === 1) {
                  condition.isSelf = 1;
                }
                if (selPatType.value !== null) {
                  condition.patType = selPatType.value;
                }
                refreshMainInfoListM6(() => {
                  //addMaininfo(formDataObj);
                  baseInfoChange(type, value, formDataObj, callback);
                  return;
                }, false);
              }

            } else {
              //#region  保存前验证是否已经存在该标本号的数据，防止同一个标本号在多台电脑扫码重复的问题

              const jgObjs = await validateIsExistMainInfo(form);
              const jgObj = jgObjs && jgObjs.length > 0 ? jgObjs[0] : null;
              if (jgObj && !IsEmpty(jgObj.patNa) && !IsEmpty(jgObj.reqNo)) {
                const type = await VXETable.modal.confirm(`该标本号已上机\n姓名: ${jgObj.patNa}\n条码号: ${jgObj.reqNo}\n上机时间: ${jgObj.createTime}\n上机人: ${jgObj.testDoctorNa}\n是否继续?`); /*不能改el  $confirm 回车事件冒泡你*/
                if (type === 'confirm') {
                  //todo
                } else {
                  //todo
                  return;
                }
              }

              //#endregion

              proxy.$emit('addMaininfo', formDataObj);
              //addMaininfo(formDataObj);
              if (callback) {
                callback();
              }

            }
          }
        }
      } else {
        //先检索列表中有没有该条码号
        let index = labMainInfoList.findIndex((p) => {
          return formatDateTime(p.sampleda, 'yyyy-MM-dd') === formatDateTime(formDataObj.sampleda, 'yyyy-MM-dd') && p.rptGroup === `${formDataObj.rptGroup}` && p.sampleNo === `${formDataObj.sampleNo}` && p.reqNo === `${formDataObj.reqNo}`;
        });

        if (index <= -1) {
          index = labMainInfoList.findIndex((p) => {
            return formatDateTime(p.sampleda, 'yyyy-MM-dd') === formatDateTime(formDataObj.sampleda, 'yyyy-MM-dd') && p.rptGroup === `${formDataObj.rptGroup}` && p.sampleNo === `${formDataObj.sampleNo}`;
          });
        }
        if (index > -1) {
          const reqNoList = await findLabMainInfoByReqNo(formDataObj.rptGroup, formDataObj.reqNo);
          if (reqNoList && reqNoList.length > 0) {
            let str = '';
            reqNoList.forEach((element) => {
              str += '→  报告单元：' + element.rptGroupNa + '\u0020\u0020\u0020\u0020上机日期：' + element.sampleda + '\u0020\u0020\u0020\u0020 条码号：' + element.sampleNo + '\n';
            });
            const type = await VXETable.modal.confirm(`条码被重复使用，相关标本如下：\n  ${str}`); /*不能改el  $confirm 回车事件冒泡你*/
            if (type === 'confirm') {
              //选中
              //继续上机
              //有：选中
              const rowObj = labMainInfoList[index];
              handleRowClick({ row: rowObj });
              if (rowObj && !IsEmpty(rowObj.id) && rowObj.reqNo === value) {
                //&& IsEmpty(rowObj.reqNo)) {
                //条码号、标本号相同直接选中不做处理
              } else if (rowObj && !IsEmpty(rowObj.id) && rowObj.reqNo !== value && !IsEmpty(rowObj.reqNo)) {
                //&& IsEmpty(rowObj.reqNo)) {
                const type = await VXETable.modal.confirm(`是否将条码号[${rowObj.reqNo}]替换为[${value}]?`);
                if (type === 'confirm') {
                  //rowObj.reqNo = value;
                  proxy.$emit('editMaininfo', rowObj, value);
                  //updateMaininfoByScanReqNo(rowObj, value);
                }
              } else if (rowObj && !IsEmpty(rowObj.id) && rowObj.reqNo !== value && IsEmpty(rowObj.reqNo)) {
                //&& IsEmpty(rowObj.reqNo)) {
                //rowObj.reqNo = value;
                proxy.$emit('editMaininfo', rowObj, value);
                //updateMaininfoByScanReqNo(rowObj, value);
              } else {
                const reqNoList = await findLabMainInfoByReqNo(formDataObj.rptGroup, formDataObj.reqNo);
                if (reqNoList && reqNoList.length > 0) {
                  let str = '';
                  reqNoList.forEach((element) => {
                    str += '→  报告单元：' + element.rptGroupNa + '\u0020\u0020\u0020\u0020上机日期：' + element.sampleda + '\u0020\u0020\u0020\u0020 条码号：' + element.sampleNo + '\n';
                  });
                  const type = await VXETable.modal.confirm(`条码被重复使用，相关标本如下：\n  ${str}`); /*不能改el  $confirm 回车事件冒泡你*/
                  if (type === 'confirm') {
                    //选中
                    //继续上机
                    //rowObj.reqNo = value;

                    updateMaininfo(rowObj, value);
                  }
                } else {
                  //选中
                  //继续上机
                  //rowObj.reqNo = value;

                  updateMaininfo(rowObj, value);
                }
              }
              if (callback) {
                callback({ isnextcode: false });
              }
            }
          } else {
            //选中
            //继续上机
            //有：选中
            const rowObj = labMainInfoList[index];
            handleRowClick({ row: rowObj });
            if (rowObj && !IsEmpty(rowObj.id) && rowObj.reqNo === value) {
              //&& IsEmpty(rowObj.reqNo)) {
              //条码号、标本号相同直接选中不做处理
            } else if (rowObj && !IsEmpty(rowObj.id) && rowObj.reqNo !== value && !IsEmpty(rowObj.reqNo)) {
              //&& IsEmpty(rowObj.reqNo)) {
              const type = await VXETable.modal.confirm(`是否将条码号[${rowObj.reqNo}]替换为[${value}]?`);
              if (type === 'confirm') {
                //rowObj.reqNo = value;
                proxy.$emit('editMaininfo', rowObj, value);
                //updateMaininfoByScanReqNo(rowObj, value);
              }
            } else if (rowObj && !IsEmpty(rowObj.id) && rowObj.reqNo !== value && IsEmpty(rowObj.reqNo)) {
              //&& IsEmpty(rowObj.reqNo)) {
              //rowObj.reqNo = value;
              proxy.$emit('editMaininfo', rowObj, value);
              //updateMaininfoByScanReqNo(rowObj, value);
            } else {
              const reqNoList = await findLabMainInfoByReqNo(formDataObj.rptGroup, formDataObj.reqNo);
              if (reqNoList && reqNoList.length > 0) {
                let str = '';
                reqNoList.forEach((element) => {
                  str += '→  报告单元：' + element.rptGroupNa + '\u0020\u0020\u0020\u0020上机日期：' + element.sampleda + '\u0020\u0020\u0020\u0020 条码号：' + element.sampleNo + '\n';
                });
                const type = await VXETable.modal.confirm(`条码被重复使用，相关标本如下：\n  ${str}`); /*不能改el  $confirm 回车事件冒泡你*/
                if (type === 'confirm') {
                  //选中
                  //继续上机
                  //rowObj.reqNo = value;

                  updateMaininfo(rowObj, value);
                }
              } else {
                //选中
                //继续上机
                //rowObj.reqNo = value;

                updateMaininfo(rowObj, value);
              }
            }
            if (callback) {
              callback({ isnextcode: false });
            }
          }
        } else {
          const reqNoList = await findLabMainInfoByReqNo(formDataObj.rptGroup, formDataObj.reqNo);
          if (reqNoList && reqNoList.length > 0) {
            let str = '';
            reqNoList.forEach((element) => {
              str += '→  报告单元：' + element.rptGroupNa + '\u0020\u0020\u0020\u0020上机日期：' + element.sampleda + '\u0020\u0020\u0020\u0020 条码号：' + element.sampleNo + '\n';
            });
            const type = await VXETable.modal.confirm(`条码被重复使用，相关标本如下：\n  ${str}`); /*不能改el  $confirm 回车事件冒泡你*/
            if (type === 'confirm') {
              //先后端验证有无上机
              const isHasRow = await findLabMainInfoByPrimaryData(formDataObj.rptGroup, formDataObj.sampleda, formDataObj.sampleNo);

              //1、有则提示
              if (isHasRow && isHasRow.length > 0) {
                //#region  保存前验证是否已经存在该标本号的数据，防止同一个标本号在多台电脑扫码重复的问题

                const jgObj = isHasRow && isHasRow.length > 0 ? isHasRow[0] : null;
                if (jgObj && !IsEmpty(jgObj.patNa) && !IsEmpty(jgObj.reqNo)) {
                  const type = await VXETable.modal.confirm(`该标本号已上机\n姓名: ${jgObj.patNa}\n条码号: ${jgObj.reqNo}\n上机时间: ${jgObj.createTime}\n上机人: ${jgObj.testDoctorNa}\n是否继续?`); /*不能改el  $confirm 回车事件冒泡你*/
                  if (type === 'confirm') {
                    //todo
                  } else {
                    //todo
                    return;
                  }
                }
                //#endregion

                //选中
                //继续上机
                //isHasRow[0].reqNo = value;

                updateMaininfo(isHasRow[0], value);
              }

              //2、无：新增
              if (!isHasRow || isHasRow.length <= 0) {
                form.id = '';
                form.reqNo = value;
                form.rptGroup = formDataObj.rptGroup;
                form.sampleNo = formDataObj.sampleNo;
                form.sampleda = formDataObj.sampleda;
                if (isMultiFilterState()) {
                  if (!smsjbqcsxtj) {
                    //先清空多条件筛选
                    state.value = 0;
                    isSelfRpt.value = 0;
                    selPatType.value = null;
                    let condition = { stateCode: state.value } as any;
                    if (isSelfRpt.value === 1) {
                      condition.isSelf = 1;
                    }
                    if (selPatType.value !== null) {
                      condition.patType = selPatType.value;
                    }
                    refreshMainInfoListM6(() => {
                      //addMaininfo(formDataObj);
                      baseInfoChange(type, value, formDataObj, callback);
                      return;
                    }, false);

                  } else {
                    proxy.$emit('addMaininfo', form);
                    // addMaininfo(form, () => {
                    //   if (callback) {
                    //     callback();
                    //   }
                    // });
                    return;
                  }
                } else {
                  proxy.$emit('addMaininfo', form);
                  // addMaininfo(form, () => {
                  //   if (callback) {
                  //     callback();
                  //   }
                  // });
                  return;
                }
              }
            }
          } else {
            //先后端验证有无上机
            const isHasRow = await findLabMainInfoByPrimaryData(formDataObj.rptGroup, formDataObj.sampleda, formDataObj.sampleNo);

            //1、有则提示
            if (isHasRow && isHasRow.length > 0) {
              //#region  保存前验证是否已经存在该标本号的数据，防止同一个标本号在多台电脑扫码重复的问题

              const jgObj = isHasRow && isHasRow.length > 0 ? isHasRow[0] : null;
              if (jgObj && !IsEmpty(jgObj.patNa) && !IsEmpty(jgObj.reqNo)) {
                const type = await VXETable.modal.confirm(`该标本号已上机\n姓名: ${jgObj.patNa}\n条码号: ${jgObj.reqNo}\n上机时间: ${jgObj.createTime}\n上机人: ${jgObj.testDoctorNa}\n是否继续?`); /*不能改el  $confirm 回车事件冒泡你*/
                if (type === 'confirm') {
                  //todo
                } else {
                  //todo
                  return;
                }
              }

              //#endregion
              //选中
              //继续上机
              //isHasRow[0].reqNo = value;

              updateMaininfo(isHasRow[0], value);
              if (callback) {
                callback();
              }
            }
            //2、无：新增
            if (!isHasRow || isHasRow.length <= 0) {
              form.id = '';
              form.reqNo = value;
              form.rptGroup = formDataObj.rptGroup;
              form.sampleNo = formDataObj.sampleNo;
              form.sampleda = formDataObj.sampleda;
              if (isMultiFilterState()) {
                if (!smsjbqcsxtj) {
                  //先清空多条件筛选
                  state.value = 0;
                  isSelfRpt.value = 0;
                  selPatType.value = null;
                  let condition = { stateCode: state.value } as any;
                  if (isSelfRpt.value === 1) {
                    condition.isSelf = 1;
                  }
                  if (selPatType.value !== null) {
                    condition.patType = selPatType.value;
                  }
                  refreshMainInfoListM6(() => {
                    //addMaininfo(formDataObj);
                    baseInfoChange(type, value, formDataObj, callback);
                    return;
                  }, false);

                } else {
                  proxy.$emit('addMaininfo', formDataObj);
                  //addMaininfo(formDataObj);
                  if (callback) {
                    callback();
                  }
                }
              } else {
                proxy.$emit('addMaininfo', formDataObj);
                //addMaininfo(formDataObj);
                if (callback) {
                  callback();
                }
              }
            }
          }
        }
      }
      break;
    default:
      break;
  }
  proxy.$emit('changeDisable', null);
}

/**右键菜单事件
 * @param menu 菜单对象
 * @param row 右键行对象
 * @param column 右键列对象
 */
function contextMenuClickEvent({ menu, row, column }) {
  console.log('menu', menu);
  console.log('row', row);
  console.log('column', column);

  const $table = tableTestListRef.value;
  switch (menu.code) {
    case 'Reload':
      refreshMainInfoList();
      break; //
    case 'Delete':
      deleteMainInfo();
      break;
    case 'Copy':
      if (row && column) {
        if (!IsEmpty(row[column.field]) && XEClipboard.copy(row[column.field])) {
          VxeMessage('已将单元格内容复制到剪贴板', VxeNotifyType.success);
        } else {
          XEClipboard.copy('空');
        }
      }
      break;
    case 'Edit':
      if (testListEditRef.value) {
        testListEditRef.value?.initPage(row);
      }
      break;
    case 'DeleteMany':
      if (testListBatchHandleRef.value) {
        testListBatchHandleRef.value?.initPage(row, menu, form.sampleda, form.rptGroup, 1);
      }
      break;
    case 'FirstReviewMany':
      if (testListBatchHandleRef.value) {
        testListBatchHandleRef.value?.initPage(row, menu, form.sampleda, form.rptGroup, 1);
      }
      break;
    case 'ReviewMany':
      if (testListBatchHandleRef.value) {
        testListBatchHandleRef.value?.initPage(row, menu, form.sampleda, form.rptGroup, 1);
      }
      break;
    case 'PrintMany':
      if (testListBatchHandleRef.value) {
        testListBatchHandleRef.value?.initPage(row, menu, form.sampleda, form.rptGroup, 1);
      }
      break;
    case 'TRansToQc':
      transToIqcMethod(row);
      break;
    case 'ResultMerge':
      //合并结果
      resultMerge(row);
      break;
    case 'CancelTest':
      noticeHisRefound(row);
      break;
    case 'FindRpt':
      showRptSearch.value = true;
      proxy.$nextTick(() => {
        setTimeout(async () => {
          await rptSearchRef.value?.initPage(row);
        }, 10);
      });
      break;
    case 'hideColumn':
      if ($table) {
        $table.hideColumn(column);
      }
      break;
    case 'showAllColumn':
      if ($table) {
        $table.resetColumn();
      }
      break;
    case 'CaSignData':
      getCaSignData(row);
      break;
    default:
      break;
  }
}
/** 转质控 */
function transToIqcMethod(row: any) {
  const data = { maininfoId: row.id };
  const url = '/api/qc/qcMaterialItemResult/transToQcResultByMainInfo';
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      VxeMessage(res.status.msg, VxeNotifyType.success);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

/** 合并结果 */
function resultMerge(row: any) {
  const data = { labMaininfo: row };
  const url = '/lab/maininfo/resultMerge';
  proxy.$http
    .post(url, { rptGroup: row.rptGroup, sampleda: row.sampleda, patNo: row.patNo, sampleNo: row.sampleNo })
    .then((res: any) => {
      handleRowClick({ row });
      VxeMessage(res.status.msg, VxeNotifyType.success);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

let labMainByReqNoList = reactive([]); //申请报告列表

/**关闭窗体 */
function cancelEqEvent() {
  showMainByReq.value = false;
}
function confirmCancelReqEvent() {
  const sltMainInfos = (proxy.$refs.mainByReqNoTableRef as any).getCheckboxRecords();

  let newList = sltMainInfos.filter((item: any) => !IsEmpty(item.isChk) && item.isChk > 0);
  if (newList.length > 0) {
    //有已审核数据不能提交
    VxeMessageMax('存在审核数据，请先取消审核', VxeNotifyType.error);
  } else {
    const ar = tableTestListRef.value?.getCurrentRecord();

    const data = { uptedLabMainInfos: sltMainInfos, curMainInfo: ar };
    const url = '/lab/maininfo/noticeHisRefoundList';
    proxy.$http
      .post(url, data)
      .then(async (res: any) => {
        showMainByReq.value = false;
        const ci = tableTestListRef.value?.getRowIndex(ar);
        await tableTestListRef.value?.remove(ar);
        labMainInfoList.splice(ci, 1);
        if (ci <= labMainInfoList.length - 1) {
          tableTestListRef.value?.setCurrentRow(labMainInfoList[ci]);
          tableTestListRef.value?.focus();
          const _row = Object.assign({}, labMainInfoList[ci]);
          handleRowClick({ row: _row });
        } else {
          handleRowClick({ row: labMainInfoList.length > 0 ? labMainInfoList[labMainInfoList.length - 1] : null });
        }
        VxeMessage(res.status.msg, VxeNotifyType.success);
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  }
}

async function noticeHisRefound(row: any) {
  labMainByReqNoList.length = 0;
  const ar = tableTestListRef.value?.getCurrentRecord();
  if (row.isChk == '2') {
    VxeMessage('标本已上机禁止取消', VxeNotifyType.error);
    return;
  }
  const data = { id: row.id };
  const url = '/lab/maininfo/noticeHisRefound';
  proxy.$http
    .post(url, data)
    .then(async (res: any) => {
      if (res && res.status && res.status.code && res.status.code === 100) {
        labMainByReqNoList.push(...res.data);
        //有其他上机记录，需要弹窗处理
        //查看是否有已审核的数据
        showMainByReq.value = true;
        proxy.$nextTick(() => {
          const $table = proxy.$refs.mainByReqNoTableRef as any;
          if ($table) {
            setTimeout(async () => {
              $table.clearCheckboxRow();
              $table.setAllCheckboxRow(true);
            }, 50);
          }
        });
        return;
      }

      const ci = tableTestListRef.value?.getRowIndex(ar);
      await tableTestListRef.value?.remove(ar);
      labMainInfoList.splice(ci, 1);
      if (ci <= labMainInfoList.length - 1) {
        tableTestListRef.value?.setCurrentRow(labMainInfoList[ci]);
        tableTestListRef.value?.focus();
        const _row = Object.assign({}, labMainInfoList[ci]);
        handleRowClick({ row: _row });
      } else {
        handleRowClick({ row: labMainInfoList.length > 0 ? labMainInfoList[labMainInfoList.length - 1] : null });
      }
      VxeMessage(res.status.msg, VxeNotifyType.success);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
function getCaSignData(row: any) {
  showCaSingData.value = true;
  Object.assign(caForm, {});
  caForm.caSignOri = row.caSignOri;
  caForm.caSignSec = row.caSignSec;
  caForm.caTimestamp = row.caTimestamp;
}

/**切换模板面板显示
 */
function toggleItemTemplatePanel() {
  isShowItemTemplatePanel.value = !isShowItemTemplatePanel.value;
}
/**标本号修改成功返回 */
function mainInfoUptSuccess(row) {
  if (tableTestListRef.value) {
    const i = labMainInfoList.findIndex((p) => p.id === row.id); //tableTestListRef.value?.getRowIndex(row);
    if (i !== -1) {
      Object.assign(labMainInfoList[i], row);
      mainInfoSort(labMainInfoList);
      const ii = labMainInfoList.findIndex((p) => p.id === row.id);
      proxy.$forceUpdate();
      proxy.$nextTick(async () => {
        handleRowClick({ row: labMainInfoList[ii] });
        if (tableTestListRef.value) {
          await tableTestListRef.value?.reloadData(labMainInfoList);
        }
      });
    }
  }
}
/**批量操作完成
 * @param rows 本次批量操作完成行集合
 * @param actflag 本次批量操作完成行集合 1:更新现有数据  2:重新刷新列表
 */
function mainInfoBatchUptSuccess(rows, actflag = 1) {
  let ci = -1;
  if (tableTestListRef.value) {
    const r = tableTestListRef.value?.getCurrentRecord();
    ci = tableTestListRef.value?.getRowIndex(r); //labMainInfoList.findIndex(p => p.id === r.id);//
  }
  labMainInfoList.forEach((m) => {
    rows.forEach((op) => {
      if (m.id === op.id) {
        op.sexNa = m.sexNa;
        op.patTypeNa = m.patTypeNa;
        op.reqDeptNa = m.reqDeptNa;
        op.reqDoctorNa = m.reqDoctorNa;
        op.sampleTypeNa = m.sampleTypeNa;
        op.testDoctorNa = m.testDoctorNa;
        Object.assign(m, op);
      }
    });
  });
  proxy.$forceUpdate();
  proxy.$nextTick(async () => {
    if (tableTestListRef.value) {
      await tableTestListRef.value?.reloadData(labMainInfoList);
      if (ci > 0) {
        handleRowClick({ row: labMainInfoList[ci] });
      }
    }
    /**放在此位置 刷新后能够选中一条数据 */
    if (actflag === 2) {
      refreshMainInfoList();
    }
  });
}
/**定位回车触发
 * @param e 事件源
 */
function keyValueAnchorKeyDown(e) {
  if (e && e.$event && !IsEmpty(e.$event.keyCode) && e.$event.keyCode === 13 && !IsEmpty(e.value)) {
    //执行搜索
    const a = labMainInfoList.filter((p) => (p.patNa && p.patNa.includes(keyValueAnchor.value)) || (p.reqNo && p.reqNo.includes(keyValueAnchor.value)) || (p.patNo && p.patNo.includes(keyValueAnchor.value)) || (p.bedNo && p.bedNo.includes(keyValueAnchor.value)));
    if (a && a.length > 0) {
      if (anchorKeyDownCount.value <= a.length - 1) {
        handleRowClick({ row: a[anchorKeyDownCount.value] });
        anchorKeyDownCount.value++;
      } else {
        anchorKeyDownCount.value = 0;
        handleRowClick({ row: a[0] });
      }
    } else {
      anchorKeyDownCount.value = 0;
    }
  }
}
/**锚点定位关键字发生改变
 *
 */
function keyValueAnchorChange(e) {
  anchorKeyDownCount.value = 0;
}
/**是否是条件状态 */
function isMultiFilterState() {
  if (!IsEmpty(state.value) && state.value != 0) {
    return true;
  }
  if (!IsEmpty(selPatType.value) && selPatType.value != null) {
    return true;
  }
  if (!IsEmpty(isSelfRpt.value) && isSelfRpt.value != 0) {
    return true;
  }
  return false;
}

watch(
  () => storeObj.wklActionFlag,
  (n, o) => {
    if (IsEmpty(n) || n <= 0) {
      return;
    }
    RefreshWKLResultsQuiert();
  },
  { deep: true, immediate: false }
);

function RefreshWKLResultsQuiert() {
  if (!IsEmpty(storeObj.maininfoObj)) {
    let curMainInfo: any = storeObj.maininfoObj;
    //根据ID 查看列表中是否存在此数据
    //如果存在更新
    //如果不存在则新增
    const i = labMainInfoList.findIndex((p) => p.id === curMainInfo.id);
    if (i > -1) {
      //根据id查询
      const url = '/lab/maininfoBac/findMainInfoById';
      proxy.$http
        //注意此处的数据条数
        .get(url, {
          params: {
            id: curMainInfo.id
          }
        })
        .then((res: any) => {
          if (res.status.code === 1) {
            const mainObj = res.data;
            Object.assign(labMainInfoList[i], mainObj);
            if (form.id == curMainInfo.id) {
              handleRowClick({ row: labMainInfoList[i] });
            }
          }
        })
        .catch((err: any) => {
          // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
        });
    } else {
      if (curMainInfo.sampleda == form.sampleda && curMainInfo.rptGroup == form.rptGroup && curMainInfo.orgId == form.orgId) {
        //根据id查询
        const url = '/lab/maininfoBac/findMainInfoById';
        proxy.$http
          //注意此处的数据条数
          .get(url, {
            params: {
              id: curMainInfo.id
            }
          })
          .then((res: any) => {
            if (res.status.code === 1) {
              const mainObj = res.data;
              appendMainInfoToList(mainObj);
            }
          })
          .catch((err: any) => {
            // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
          });
      }
    }
  }
}

// 弹框 表格复选框(是否允许用户手动勾选)
function checCheckboxkMethod2({ row }: any) {
  return false;
}
</script>
<style lang="scss" scoped>
#testlistpanel {
  height: 100%;

  .footer-vxe-toolbar {
    padding: 0.3em !important;
  }

  :deep(.footer-vxe-toolbar .vxe-input--inner) {
    line-height: unset !important;
    height: 95% !important;
  }
}

//初审
:deep(.is-first-reviewed) {
  content: '初' !important;
}

:deep(.is-first-reviewed::after) {
  content: '初' !important;
  color: #fff !important;
}

:deep(.flag-cell) {
  .vxe-cell {
    padding: 0 2px !important;
  }
}
</style>
